package by.airlanterns.web;

import by.airlanterns.dto.User;
import by.airlanterns.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Sergey
 * Date: 26.01.13
 * Time: 16:30
 * To change this template use File | Settings | File Templates.
 */

@Controller
public class BaseController {

    private Map<String, Object> model = new HashMap<String, Object>();

    public static final int MAIN_CATEGORY_ID = 1;
    public static final int SECOND_CATEGORY = 2;

    public static final String ROLE_USER = "ROLE_USER";
    public static final String ROLE_ADMIN = "ROLE_ADMIN";

    @Autowired
    private UserService userService;


    public Map<String, Object> getModel() {
        model.put("user", getCurrentUser());
        return model;
    }

    public User getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Object obj = auth.getPrincipal();
        String username = "";
        if (obj instanceof UserDetails) {
            username = ((UserDetails) obj).getUsername();
        } else {
            username = obj.toString();
        }
        List<User> list = null;
        if (!username.equals("anonymousUser")) {
            list = userService.findUserByLogin(username);
            return list.get(0);
        } else {
            return new User();
        }

    }

}
